package smtpserver

import (
	"crypto/tls"
	"fmt"
	"strings"

	"github.com/nosch/smtpoll/config"
)

// 将字符串转换为 TLS 版本
func parseTLSVersion(version string) (uint16, error) {
	switch strings.ToLower(version) {
	case "tls1.0":
		return tls.VersionTLS10, nil
	case "tls1.1":
		return tls.VersionTLS11, nil
	case "tls1.2":
		return tls.VersionTLS12, nil
	case "tls1.3":
		return tls.VersionTLS13, nil
	default:
		return 0, fmt.Errorf("不支持的TLS版本: %s", version)
	}
}

// 将字符串转换为加密套件
func parseCipherSuite(suite string) (uint16, error) {
	switch suite {
	case "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384":
		return tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, nil
	case "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384":
		return tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, nil
	case "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305":
		return tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305, nil
	case "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305":
		return tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305, nil
	default:
		return 0, fmt.Errorf("不支持的加密套件: %s", suite)
	}
}

// 创建TLS配置
func createTLSConfig(config *config.TLSConfig) (*tls.Config, error) {
	if !config.Enabled {
		return nil, nil
	}

	// 加载证书
	cert, err := tls.LoadX509KeyPair(config.CertFile, config.KeyFile)
	if err != nil {
		return nil, fmt.Errorf("加载证书失败: %v", err)
	}

	// 解析TLS版本
	minVersion, err := parseTLSVersion(config.MinVersion)
	if err != nil {
		return nil, err
	}
	maxVersion, err := parseTLSVersion(config.MaxVersion)
	if err != nil {
		return nil, err
	}

	// 解析加密套件
	var cipherSuites []uint16
	for _, suite := range config.CipherSuites {
		cs, err := parseCipherSuite(suite)
		if err != nil {
			return nil, err
		}
		cipherSuites = append(cipherSuites, cs)
	}

	return &tls.Config{
		Certificates:             []tls.Certificate{cert},
		MinVersion:               minVersion,
		MaxVersion:               maxVersion,
		CipherSuites:             cipherSuites,
		PreferServerCipherSuites: true,
	}, nil
}
